package com.sh.data.engine.common.annotation;


import org.hibernate.validator.internal.util.logging.Log;
import org.hibernate.validator.internal.util.logging.LoggerFactory;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.invoke.MethodHandles;

/**
 * @author xinyan
 * @date 2022/2/15 14:08
 */

public class TrimLengthValidator implements ConstraintValidator<TrimLength, String> {
    private static final Log LOG = LoggerFactory.make(MethodHandles.lookup());
    private int min;

    private int max;

    @Override
    public void initialize(TrimLength constraintAnnotation) {
        min = constraintAnnotation.min();
        max = constraintAnnotation.max();
        this.validateParameters();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (value == null) {
            return true;
        } else {
            value = value.trim();
            int length = value.length();
            return length >= this.min && length <= this.max;
        }
    }

    private void validateParameters() {
        if (this.min < 0) {
            throw LOG.getMinCannotBeNegativeException();
        } else if (this.max < 0) {
            throw LOG.getMaxCannotBeNegativeException();
        } else if (this.max < this.min) {
            throw LOG.getLengthCannotBeNegativeException();
        }
    }
}
